from sqlalchemy import Column, String, Integer, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from init.mysql import engine

Base = declarative_base()


class StockMasterFund(Base):
    __tablename__ = 'stock_master_fund'
    id = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(String(6))
    t = Column(String(10))
    zdf = Column(Float)
    lrzj = Column(Float)
    lrl = Column(Float)
    lczj = Column(Float)
    jlr = Column(Float)
    jlrl = Column(Float)
    shlrl = Column(Float)

    def __init__(self, code, t, zdf, lrzj, lrl, lczj, jlr, jlrl, shlrl):
        self.code = code
        self.t = t
        self.zdf = zdf
        self.lrzj = lrzj
        self.lrl = lrl
        self.lczj = lczj
        self.jlr = jlr
        self.jlrl = jlrl
        self.shlrl = shlrl

    @staticmethod
    def insert_or_update(code, data_list):
        session = sessionmaker(bind=engine)()
        for data in data_list:
            existing_stock_master_fund = session.query(StockMasterFund).filter_by(code=code, t=data['t']).first()
            if existing_stock_master_fund:
                existing_stock_master_fund.zdf = data['zdf']
                existing_stock_master_fund.lrzj = data['lrzj']
                existing_stock_master_fund.lrl = data['lrl']
                existing_stock_master_fund.lczj = data['lczj']
                existing_stock_master_fund.jlr = data['jlr']
                existing_stock_master_fund.jlrl = data['jlrl']
                existing_stock_master_fund.shlrl = data['shlrl']
            else:
                session.add(StockMasterFund(code=code, t=data['t'], zdf=data['zdf'], lrzj=data['lrzj'], lrl=data['lrl'],
                                            lczj=data['lczj'], jlr=data['jlr'], jlrl=data['jlrl'], shlrl=data['shlrl']))
        session.commit()
        session.close()


Base.metadata.create_all(engine)
